<template>
    <el-dialog :title="dialogTitle" :visible="visible">
      <el-form :model="form">
        <el-form-item label="分类名称：" :label-width="formLabelWidth">
          <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="排序：" :label-width="formLabelWidth">
          <el-input v-model="form.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSave">
          确定
        </el-button>
        <el-button v-show="type !== 'xiugai'"  type="primary" @click="handleSubmit">
          保存并继续添加
        </el-button>
      </div>
    </el-dialog>
  </template>
  <script>
import {createCaipin, changeRevise} from "@/api/fenlei"
  export default {
    name: 'AddDialog',
    props:{
      currentRow: {
      type: Object,
      default: () => ({})
      },
      visible: {
      type: Boolean,
      default: false
      },
      type: {
      type: String,
      required: true,
      validator: value => ['caipin', 'taocan','xiugai'].includes(value)
      },
    }, 
    data() {
      return {
        form: { name: '', sort: '', id: '' },
        formLabelWidth: '120px'
      }
    },
    watch: {
    currentRow: {
      handler(newVal) {
        if (this.type === 'xiugai') {
          this.form = newVal 
        }else{
          this.form={}
        }
      },
      immediate: true,
      deep: true
    }
  },
    computed: {
    dialogTitle() {
      return this.type === 'xiugai' 
      ? '修改分类' 
      : this.type === 'caipin' 
        ? '新增菜品分类' 
        : '新增套餐分类'
    }
  },
    methods: {
      handleCancel() {
        if (this.type==='xiugai'){
          this.$emit('update:visible', false)
        }else{
          this.$emit('update:visible', false)
          this.form={}
        }
      },
      handleSave() {
        if (this.type === 'xiugai'){
          changeRevise(this.form).then(()=>{
          this.form={}
          this.$emit('save-completed')
          this.$emit('update:visible', false)
          })
        }else{
          createCaipin(this.form).then(()=>{
          this.form={}
          this.$emit('save-completed')
          this.$emit('update:visible', false)
        })
        }   
      },
      handleSubmit() {
          createCaipin(this.form).then(()=>{
          this.form={}
          this.$emit('save-completed')
        })
        }
    }
  }
  </script>